<template>
  <div>
    <div class="bear"></div>

    <div class="mound1"></div>

    <div class="mound2"></div>

    <div class="login-main w">
      <div class="login_title"><h2>Welcome</h2></div>

      <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
        <el-form-item class="username" prop="username">
          <el-input
            placeholder="请输入账号"
            v-model="loginForm.username"
          ></el-input>
        </el-form-item>

        <el-form-item class="password" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item class="login_btn">
          <el-button
            type="primary"
            @click="submitLoginForm"
            class="login_faster"
            >立即登录</el-button
          >
          <el-button type="info" @click="resetLoginForm" class="reset"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "login",
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },

      // 表单的验证规则
      loginFormRules: {
        // 验证账号是否合法
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 2,
            max: 8,
            message: "长度在 2 到 8 个字符",
            trigger: "blur",
          },
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 表单重置
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields();
    },

    // 点击登录按钮事件
    submitLoginForm() {
      // 先对表单进行预校验
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) return;
        var { data: res } = await this.$http.post("login", this.loginForm);

        if (res.meta.status !== 200) {
          this.$message.error({
            message: "用户不存在",
          });
        } else {
          this.$message.success("登录成功");
        }

        // 1.将登录成功后的 token 进行存储，保存到客户端的sessionStorage中
        window.sessionStorage.setItem("token", res.data.token);

        //2.通过编程导航跳转到后台主页，路由地址为 /home
        this.$router.push("/home");
      });
    },
  },
};
</script>

<style scoped>
@import "../assets/css/login.css";
</style>
